layui.config({
    base: Feng.ctxPath+'/static/plugins/step-lay/'
}).use(['form', 'step'], function () {
    var $ = layui.$
        , form = layui.form
        , step = layui.step;

    var selectClassIds="";
    var firstClassId="";



    var classUpdate = {
        orgId: $("#orgId").val(),
        schoolYear: $("#schoolYear").val(),
        selectedClassMap: {},//已选班级
        selectedPhaseGradeMap: {},//已选学段&年级
        classIds: "",
        firstClassId: "",
        lastClassId: "",
        oneHtml: "",
        requestAjax(url, params, callback, returntype) {
            var returnData;
            if (returntype == "html") {
                dataType = "html";
            } else {
                dataType = "json";
            }

            if (url === Feng.ctxPath + "/ptClass/classupdate/editClass") {
                var parString = "";
                for (var key in params) {
                    parString += key + "=" + params[key] + "&";
                }
                if (parString.length > 0) {
                    parString = parString.substring(0, parString.length - 1);
                    parString = "?" + parString;
                }
                window.location.href = Feng.ctxPath + "/ptClass/classupdate/editClass" + parString;
                return false;
            }
            if (url ===Feng.ctxPath + "/ptClass/classupdate/editClassTeacher") {
                var parString = "";
                for (var key in params) {
                    parString += key + "=" + params[key] + "&";
                }
                if (parString.length > 0) {
                    parString = parString.substring(0, parString.length - 1);
                    parString = "?" + parString;
                }
                window.location.href = Feng.ctxPath + "/ptClass/classupdate/editClassTeacher" + parString;
                return false;
            }
            if (url ===Feng.ctxPath + "/ptClass/classupdate/editClassStudent") {
                var parString = "";
                for (var key in params) {
                    parString += key + "=" + params[key] + "&";
                }
                if (parString.length > 0) {
                    parString = parString.substring(0, parString.length - 1);
                    parString = "?" + parString;
                }
                window.location.href = Feng.ctxPath + "/ptClass/classupdate/editClassStudent" + parString;
                return false;
            }
            if (url === Feng.ctxPath + "/ptClass/classupdate/toXjClassSuccess") {
                var parString = "";
                for (var key in params) {
                    parString += key + "=" + params[key] + "&";
                }
                if (parString.length > 0) {
                    parString = parString.substring(0, parString.length - 1);
                    parString = "?" + parString;
                }
                window.location.href = Feng.ctxPath + "/ptClass/classupdate/toXjClassSuccess" + parString;
                return false;
            }
            $.ajax({
                type: "post",
                async: false,
                cache: false,
                dataType: dataType,
                url: url,
                data: params,
                success: function (data) {
                    if (data != null) {
                        returnData = data;
                    }
                    if (callback) {
                        callback(data);
                    }
                }
            });
            return returnData;
        },
        changeClassStatus: function (pathUrl) {
            if (pathUrl==='selectclassindex') {
                classUpdate.classIds = "";
                classUpdate.firstClassId = "";
                classUpdate.lastClassId = "";
            }

            url = Feng.ctxPath + "/ptClass/classupdate/changeClassStatus";
            $(".update_classIds input:checked").each(function (i, el) {
                classUpdate.classIds += $(el).val() + ",";
                selectClassIds=classUpdate.classIds;
                if (i == 0) {
                    classUpdate.firstClassId = $(el).val();
                    firstClassId=classUpdate.firstClassId;
                }
                if (i == $(".update_classIds input:checked").length - 1) {
                    classUpdate.lastClassId = $(el).val();
                }
            });
            var params = {
                "classIds": classUpdate.classIds,
                "status": 1
            };
            classUpdate.requestAjax(url, params, null);
            classUpdate.toEditClass(classUpdate.firstClassId, pathUrl,selectClassIds);
        },
        toEditClass: function (fromclassId, pathUrl,selectClassIds) {
            if (pathUrl === 'editClass') {
                url = Feng.ctxPath + "/ptClass/classupdate/" + pathUrl;
                var params = {
                    "fromClassId": fromclassId,
                    "orgId": classUpdate.orgId,
                    "classIds": selectClassIds,
                    "schoolYear": classUpdate.schoolYear,
                };
            } else {
                classUpdate.schoolYear = $("#schoolYear1").val() - 1;
                window.location.href = Feng.ctxPath + "/ptClass/classupdate/" + pathUrl + "?orgId=" + classUpdate.orgId + "&schoolYear=" + classUpdate.schoolYear;
                return false;
            }
            var callback = classUpdate.appendHtml;
            var type = "html";
            classUpdate.requestAjax(url, params, callback, type);
            return false;
        },
        //设置任课教师
        tosetTeacher: function (fromclassId) {
            url = Feng.ctxPath + "/ptClass/classupdate/editClassTeacher";
            var params = {
                "fromClassId": fromclassId,
                "classIds": selectClassIds,
                "schoolYear": classUpdate.schoolYear,
            };
            var callback = classUpdate.appendHtml;
            var type = "html";
            classUpdate.requestAjax(url, params, callback, type)
        },
        //设置班级学生
        tosetStduent: function (fromclassId) {
            url = Feng.ctxPath + "/ptClass/classupdate/editClassStudent";
            var params = {
                "fromClassId": fromclassId,
                "classIds": selectClassIds,
                "schoolYear": classUpdate.schoolYear,
            };
            var callback = classUpdate.appendHtml;
            var type = "html";
            classUpdate.requestAjax(url, params, url, type)

        },


        toEditTeacher: function (fromclassId) {
            url = Feng.ctxPath + "/ptClass/classupdate/editClassTeacher";
            var params = {
                "fromClassId": fromclassId,
                "orgId": classUpdate.orgId,
                "classIds": selectClassIds,
                "schoolYear": classUpdate.schoolYear,
            };
            var callback = classUpdate.appendHtml;
            var type = "html";
            classUpdate.requestAjax(url, params, callback, type)
        },
        toEditStudent: function (fromclassId) {
            url = Feng.ctxPath + "/ptClass/classupdate/editClassStudent";
            var params = {
                "fromClassId": fromclassId,
                "orgId": classUpdate.orgId,
                "classIds": classUpdate.classIds,
                "schoolYear": classUpdate.schoolYear,
            };
            var callback = classUpdate.appendHtml;
            var type = "html";
            classUpdate.requestAjax(url, params, callback, type)
        },
        appendHtml: function (html) {
            window.location.href = html;
        },

        checkTeacher: function (form) {
            var $form = $(form);
            if (!$form.valid()) {
                return false;
            }
            var flag = true;
            $("#class_teacher_edit").find("div[name='class_teacher']").each(function (i, el) {
                if ($(el).find("input").eq(2).val() != "" && $(el).find("input").eq(1).val() == "") {
                    alert($(el).attr("subjectName") + "学科中该教师不存在，请重新选择");
                    flag = false;
                }
            });
            if (flag) {
                callback = classUpdate.editTeacherCallback(form);
                validateCallback(form, callback);
            }
            return false;
        },
        checkStudent: function (form, callback, confirmMsg) {
            var $form = $(form);
            if (!$form.valid()) {
                return false;
            }
            var flag = true;
            $form.find("#studentList").find("tr").each(function (index, obj) {
                if ($(obj).find("input").eq(2).val() != "" && $(obj).find("input").eq(1).val() == "") {
                    alert("第" + (index + 1) + "行的学生不存在或已经被分配到其他班级，请重新选择");
                    flag = false;
                }
            });
            if (flag) {
                callback = classUpdate.editStudentCallback(form);
                validateCallback(form, callback, confirmMsg);
            }
            return false;
        },
        toSuccess: function (classIds) {
            url = Feng.ctxPath + "/ptClass/classupdate/toXjClassSuccess";
            var params = {
                "classIds": classIds,
                "schoolYear": classUpdate.schoolYear,
            };
            var callback = classUpdate.appendHtml;
            var type = "html";
            classUpdate.requestAjax(url, params, callback, type);
        },
        continueUpdate: function () {
            $("#updateClass_class_edit").html(classUpdate.oneHtml);
// 		$("input[name='all']:checked").removeAttr("checked");
            $(".update_classIds").html("");
        },
        saveClass:function () {
        var params = {
            orgId:$("#orgId").val(),
            id:$("#id").val(),
            schoolYear:$("#schoolYear1").val(),
            fromClassId:$("#fromClassId").val(),
            name:$("#newClassNameId").val(),
            period:$("#period").val(),
            phaseId:$("#phaseId").val(),
            gradeId:$("#gradeId").val(),
            subjectType:$("#subjectType").val(),
            classType:$("#classType").val(),
            sort:$("#sort").val(),
            teacherId:$("#teacherId").val()
        };
        //提交信息
        var ajax = new $ax(Feng.ctxPath + "/ptClass/add", function(data){
            if (data.code===200){
                Feng.success(data.msg);
                selectClassIds=$("#classIds").val();
                if(!$("#twostepNext").attr("data-id")){//下一步
                    classUpdate.tosetTeacher(selectClassIds.split(",")[0]);
                }else {
                    classUpdate.toEditClass($("#twostepNext").attr("data-id"),"editClass",selectClassIds);
                }
                return false;
            }else {
                Feng.error(data.msg)
            }
        },function(data){
            Feng.error(data.msg)
        });
        ajax.set(params);
        ajax.start();
    },
        saveClassTeacher:function (data) {

            //提交信息
            var ajax = new $ax(Feng.ctxPath + "/ptClass/saveClassTeacher", function(data){
                if (data.code===200){
                    Feng.success(data.msg);
                    selectClassIds=$("#classIds").val();
                    if(!$("#threestepNext").attr("data-id")){
                        classUpdate.tosetStduent(selectClassIds.split(",")[0]);
                    }else {
                        classUpdate.toEditTeacher($("#threestepNext").attr("data-id"));
                    }
                    return false;
                }else {
                    Feng.error(data.msg)
                }
            },function(data){
                Feng.error(data.msg)
            });
            ajax.set(data);
            ajax.start();
        }
    };

    form.on('submit(formStep)', function (data) {
        if ($(".update_classIds input:checked").length < 1) {
            layer.alert("请选择需要升级的班级");
            return false;
        }
        classUpdate.changeClassStatus('editClass');
        step.next('#stepForm');
        return false;
    });

    form.on('submit(formStep2)', function (data) {
        classUpdate.saveClass();
        step.next('#stepForm');
        return false;
    });
    form.on('submit(formStep3)', function (data) {

        classUpdate.saveClassTeacher(data.field);
        step.next('#stepForm');
        return false;
    });
    form.on('submit(formStep4)', function (data) {
        selectClassIds=$("#classIds").val();
        classUpdate.classIds=selectClassIds;
        classUpdate.schoolYear=$("#schoolYear").val();
        if($("#fourstepNext").attr("data-id")===''){
            classUpdate.toSuccess(selectClassIds);
        }else {
            classUpdate.toEditStudent($("#fourstepNext").attr("data-id"));
        }
        return false;
    });
    function towPreFunction(){
        if($("#twostepPre").attr("data-id")){
            classUpdate.schoolYear=$("#schoolYear").val()-1;
            var  preClassId=($("#twostepPre").attr("data-id"));

            classUpdate.toEditClass(preClassId,"editClass",selectClassIds);
        }else {
            classUpdate.changeClassStatus('selectclassindex');
        }

    }
    function threeFunction(){
        selectClassIds=$("#classIds").val();
        selectClassIds1=(selectClassIds.substring(selectClassIds.length-1)==',')?selectClassIds.substring(0,selectClassIds.length-1):selectClassIds;
        classUpdate.lastClassId=selectClassIds1.split(',')[selectClassIds1.split(',').length -1];
        if(!$("#threestepPre").attr("data-id")){
            classUpdate.toEditClass(classUpdate.lastClassId,"editClass",selectClassIds);
        }else{
            var preClassId =$("#threestepPre").attr("data-id");
            classUpdate.toEditTeacher(preClassId);
        }

    }
    function fourPreFunction(){
        selectClassIds=$("#classIds").val();
        classUpdate.schoolYear=$("#schoolYear").val()-1;
        selectClassIds1=(selectClassIds.substring(selectClassIds.length-1)==',')?selectClassIds.substring(0,selectClassIds.length-1):selectClassIds;
        classUpdate.lastClassId=selectClassIds1.split(',')[selectClassIds1.split(',').length -1];
        if(!$("#fourstepPre").attr("data-id")){
            classUpdate.toEditTeacher(classUpdate.lastClassId);
        }else{
            var preClassId =$("#fourstepPre").attr("data-id");
            classUpdate.toEditStudent(preClassId);
        }

    }
    function endNextFunction(){
        window.location.href = Feng.ctxPath + "/ptClass/classupdate/selectclassindex?orgId="+$("#orgId").val()+"&schoolYear="+$("#schoolYear").val();
        return false;
    }
    function closeIndex(){
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);//关闭当前页
        return false;
    }
    $(".twoPre").bind("click",towPreFunction);
    $(".threePre").bind("click",threeFunction);
    $(".fourPre").bind("click",fourPreFunction);
    $(".endNext").bind("click",endNextFunction);
    $(".closeIndex").bind("click",closeIndex);
    $(document).on("click",".next",function(){
        step.next('#stepForm');
    });
    form.on('select(guanlian)', function (data) {
        $(".update_classIds").html("");
        classUpdate.selectedPhaseGradeMap["phaseId"] = $("#phaseId").val();
        var map = JSON.parse(($("#phase_gradeMap").val()));
        var gradeList = map[$("#phaseId").val()];
        var gradeOptions = "<option value=''>请选择...</option>";
        if (gradeList != null) {
            $.each(gradeList, function (n, grade) {
                gradeOptions += "<option value='" + grade.id + "' ";
                gradeOptions += ">" + grade.name + "</option>";
            });
        }
        $("#gradeId").html(gradeOptions);
        form.render();
    });
    form.on('select(changeGrade)', function (data) {
        classUpdate.selectedPhaseGradeMap["gradeId"] = $("#gradeId").val();
        var url = Feng.ctxPath + "/ptClass/classupdate/selectedclasses";
        var params = {
            "orgId": classUpdate.orgId,
            "phaseId": classUpdate.selectedPhaseGradeMap["phaseId"],
            "gradeId": classUpdate.selectedPhaseGradeMap["gradeId"],
            "schoolYear": classUpdate.schoolYear,
        };
        var callback1 =initClass;
        classUpdate.requestAjax(url, params, callback1);
        url = Feng.ctxPath + "/ptClass/classupdate/getAllClass";
        var callback2 = showClasses;
        classUpdate.requestAjax(url, params, callback2);
    });
    function initClass(data) {
        $.each(data, function (index, obj) {
            classUpdate.selectedClassMap[obj.id] = obj;
        })
    }
    form.on('checkbox(allChoose)', function (data) {
        /*此处为匹配页面属性class="itemSelect" 可任意更换*/
        $("input[class='itemSelect']").each(function () {
            this.checked = data.elem.checked;
        });
        form.render('checkbox');
    });
    function showClasses(data) {
        $(".update_classIds").html("");
        $("input[type='checkbox']").attr("checked", false);
        var html = "";
        $.each(data, function (index, obj) {
            var tipDom = "";
            if (classUpdate.selectedClassMap[obj.id] != null && classUpdate.selectedClassMap[obj.id].status == 2) {
                tipDom = "<font style='color:red;'>(已升级)</font>";
            } else if (classUpdate.selectedClassMap[obj.id] != null && classUpdate.selectedClassMap[obj.id].status == 1) {
                tipDom = "<font style='color:red;'>(正在升级)</font>";
            }
            html += '<input name="all" lay-skin="primary" class="itemSelect" type="checkbox" value="' + obj.id + '" >' + obj.name + tipDom + '</input>';
        });
        $(".update_classIds").html(html);
        form.render()
    }
});


